<?php


namespace app\command\count;


use app\common\model\CountBox;
use app\common\model\MoneyRecordModel;
use org\DingDingRobot;
use think\console\Command;
use think\console\Output;
use think\console\Input;
use think\console\input\Argument;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 宝箱统计脚本
 * Class CountBoxCommand
 * @package app\command\count
 */
class CountBoxCommand extends Command
{
    protected function configure()
    {
        $this->setName('count_box')
            ->addArgument('begin_day', Argument::OPTIONAL, '指定执行开始日期')
            ->addArgument('end_day', Argument::OPTIONAL, '指定执行截至日期')
            ->setDescription('宝箱统计脚本');
    }

    /**
     * @param Input $input
     * @param Output $output
     * @return int|void|null
     */
    protected function execute(Input $input, Output $output)
    {
        $begin_day = $input->getArgument('begin_day');
        $end_day   = $input->getArgument('end_day');

        if (empty($end_day) && empty($begin_day)) {

            # 定时任务配置在凌晨之后，默认跑前一天的数据
            $date = date('Y-m-d', strtotime(date('Y-m-d') . ' -1 day'));
            $this->buildData($date, $output);

        } elseif (!empty($begin_day) && !empty($end_day)) {

            # 跑指定日期范围的数据
            $begin_time = strtotime(date('Y-m-d 00:00:00', strtotime($begin_day)));
            $end_time   = strtotime(date('Y-m-d 23:59:59', strtotime($end_day)));

            for ($i = $begin_time; $i < $end_time; $i += 86400) {
                $date = date('Y-m-d', $i);
                $this->buildData($date, $output);
                $output->info($date);
            }

        } elseif (!empty($begin_day)) {
            # 跑指定日期的数据
            $date = date('Y-m-d', strtotime($begin_day));
            $this->buildData($date, $output);
            $output->info($date);
        }
    }


    /**
     * 日期    参与人数    金币总数    1个    2个    3个    4个    5个    6个    7个    8个    9个    10个
     * 参与人数：领取过1次的即算参与
     * 金币总数：通过宝箱发放的总金币数（包含双倍）
     * @param string $date
     * @param Output $output
     */
    protected function buildData(string $date, Output $output)
    {
        try {
            $field = [
                "count(DISTINCT member_id) user_num", # 参与人数:领取过1次的即算参与
                "sum(amount) gold_num", # 金币总数：通过宝箱发放的总金币数（包含双倍）
            ];

            $model = MoneyRecordModel::where([
                ['write_date', '=', $date],
                ['method', 'IN', [5, 15, 17]], // 5=首页宝箱  15=转盘宝箱 17=宝箱任务
            ]);

            // 合计
            $data_count = $model->field($field)->find();

            // 当天开宝箱的用户，分别开了多少个宝箱
            $group_user = $model->group("member_id")->column("count(id) num", "member_id");
            $user_count = [];
            foreach ($group_user as $key => $val) {
                $user_count[$val] = ($user_count[$val] ?? 0) + 1;   // 个数 => 用户数
            }

            $data = [
                'record_date' => $date,
                'user_num'    => $data_count['user_num'] ?? 0,
                'gold_num'    => $data_count['gold_num'] ?? 0,
                'num_1'       => $user_count[1] ?? 0,
                'num_2'       => $user_count[2] ?? 0,
                'num_3'       => $user_count[3] ?? 0,
                'num_4'       => $user_count[4] ?? 0,
                'num_5'       => $user_count[5] ?? 0,
                'num_6'       => $user_count[6] ?? 0,
                'num_7'       => $user_count[7] ?? 0,
                'num_8'       => $user_count[8] ?? 0,
                'num_9'       => $user_count[9] ?? 0,
                'num_10'      => $user_count[10] ?? 0,
                'create_time' => time(),
            ];

            $row = CountBox::where("record_date", $date)->find();
            if ($row) {
                CountBox::update($data, ['id' => $row['id']]);
            } else {
                CountBox::insert($data);
            }
            DingDingRobot::getInstance()->pushText("宝箱统计脚本,执行完成,日期:{$date}");

        } catch (DataNotFoundException $e) {
            DingDingRobot::getInstance()->pushText("宝箱统计脚本异常，日期:{$date},内容：" . $e->getMessage());

        } catch (ModelNotFoundException $e) {
            DingDingRobot::getInstance()->pushText("宝箱统计脚本异常，日期:{$date},内容：" . $e->getMessage());

        } catch (DbException $e) {
            DingDingRobot::getInstance()->pushText("宝箱统计脚本异常，日期:{$date},内容：" . $e->getMessage());

        }
    }
}